package org.cl.persist.note.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author cl
 */
@Slf4j
@Service
public class NoteServiceImpl {

    public String[] getNoteDir() {
        List<String> noteDir = new ArrayList<>();
        File dir = new File("/opt/BOOT-INF/classes/note");
        if (dir != null && dir.isDirectory()) {
            for(File t : dir.listFiles()) {
                String filename = t.getName();
                log.info("文件有: " + filename);
                if (filename.contains(".md")) {
                    noteDir.add(filename.substring(0, filename.length() - 3));
                }
            }
        }
        if (noteDir.size() < 1) {
            return new String[] {
                    "algorithm",
                    "auth",
                    "design",
                    "docker",
                    "http",
                    "idea",
                    "java",
                    "springBoot",
                    "linux",
                    "mySql",
                    "netty",
                    "redis",
                    "swagger",
                    "tools",
                    "window",
                    "log"
            };
        }
        return noteDir.toArray(new String[noteDir.size()]);
    }

    public String getNoteContent(String name) {
        try {
            String filename = name + ".md";
            InputStream in = NoteServiceImpl.class.getClassLoader().getResourceAsStream("note/" + filename);

            if (in == null) {
                log.warn("获取不到 [" + filename + "] 文件");
                return "";
            }
            File tmpFile = new File(filename);
            FileUtils.copyInputStreamToFile(in, tmpFile);

            log.info("获取到 [" + filename + "] 文件");
            StringBuilder builder = new StringBuilder();
            FileReader fr = new FileReader(tmpFile);
            // 按行读取字符串
            int str = -1;
            while ((str = fr.read()) > -1) {
                builder.append((char)str);
            }
            fr.close();
            tmpFile.delete();
            return builder.toString();
        } catch (Exception e) {
            log.warn("获取不到文件");
            return "";
        }
    }
}
